package component.global.manager
{
	import component.controls.ui.ArrowButton;
	import component.controls.ui.ThumbButton;
	
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	public class EventMgr
	{
		public function EventMgr()
		{
			_interactiveObjects = new Dictionary(true);
		}
		
		private static var _instance:EventMgr
		
		public static function get Instance():EventMgr{
			if(_instance == null){
				_instance = new EventMgr();
			}
			return _instance;
		}
		
		/**
		 *{interactiveObject, keys, handlers}
		 */		
		private var _interactiveObjects:Dictionary;
		
		public function addEvent(interactiveObject:EventDispatcher, types:Array = null, handlers:Array = null):void{
			if(_interactiveObjects[interactiveObject] == null){
				_interactiveObjects[interactiveObject] = {interactiveObject:interactiveObject, types:types, handlers:handlers};
			} else {
				if(types == null || handlers == null)return;
				var tempTypes:Array = _interactiveObjects[interactiveObject].types;
				var tempHandlers:Array = _interactiveObjects[interactiveObject].handlers;
				
				for (var i:int = 0; i < types.length; i++) 
				{
					var isExistSame:Boolean = false;
					for (var k:int = 0; k < tempTypes.length; k++) 
					{
						if(tempTypes[k] == types[i] && tempHandlers[k] == handlers[i]){
							isExistSame = true;
						}
					}
					if(!isExistSame){
						tempTypes.push(types[i]);
						tempHandlers.push(handlers[i]);
					}
				}
				_interactiveObjects[interactiveObject].types = tempTypes;
				_interactiveObjects[interactiveObject].handlers = tempHandlers;
			}
			for (var j:int = 0; j < types.length; j++) 
			{
				interactiveObject.addEventListener(types[j],handlers[j]);
			}
		}
		
		public function removeEvent(interactiveObject:EventDispatcher, types:Array= null, handlers:Array = null):void{
			if(_interactiveObjects[interactiveObject] == null)return;
			var tempTypes:Array = types;
			var tempHandlers:Array = handlers;
			if(tempTypes == null)tempTypes = _interactiveObjects[interactiveObject].types;
			if(tempHandlers == null)tempHandlers = _interactiveObjects[interactiveObject].handlers;
			
			var wholeTypes:Array = _interactiveObjects[interactiveObject].types;
			var wholeHandlers:Array = _interactiveObjects[interactiveObject].handlers;
			
			var i:int = 0;
			while(i < tempTypes.length){
				var isFind:Boolean = false;
				for (var j:int = 0; j < wholeTypes.length; j++) 
				{
					if(wholeTypes[j] == tempTypes[i] && wholeHandlers[j] == tempHandlers[i]){
						interactiveObject.removeEventListener(wholeTypes[j],wholeHandlers[j]);
						wholeTypes.splice(j,1);
						wholeHandlers.splice(j,1);
						i=0;
						isFind = true;
						break;
					}
				}
				if(!isFind)i++;
			}
			
			if(wholeHandlers.length == 0){
				delete _interactiveObjects[interactiveObject];
			}
		}
	}
}